#!/usr/bin/env python3
"""
阿里云ECS连接诊断工具
服务器IP: 8.140.59.178
"""

import socket
import subprocess
import time
import sys
from datetime import datetime

def test_ping(host, count=4):
    """测试ping连通性"""
    print(f"🔍 测试Ping连通性: {host}")
    try:
        if sys.platform.startswith('win'):
            result = subprocess.run(['ping', '-n', str(count), host], 
                                  capture_output=True, text=True, timeout=30)
        else:
            result = subprocess.run(['ping', '-c', str(count), host], 
                                  capture_output=True, text=True, timeout=30)
        
        if result.returncode == 0:
            print("✅ Ping测试成功")
            # 分析ping结果
            output = result.stdout
            if '请求超时' in output or 'Request timeout' in output:
                print("⚠️ 有丢包现象")
            print(f"详细信息: {output.strip().split('\\n')[-1] if '\\n' in output else output.strip()}")
            return True
        else:
            print("❌ Ping测试失败")
            print(f"错误: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ Ping测试异常: {str(e)}")
        return False

def test_port(host, port, timeout=10):
    """测试端口连通性"""
    print(f"🔍 测试端口连通性: {host}:{port}")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        
        if result == 0:
            print(f"✅ 端口{port}连通正常")
            return True
        else:
            print(f"❌ 端口{port}无法连接 (错误代码: {result})")
            return False
    except Exception as e:
        print(f"❌ 端口测试异常: {str(e)}")
        return False

def test_ssh_banner(host, port=22, timeout=10):
    """测试SSH服务响应"""
    print(f"🔍 测试SSH服务响应: {host}:{port}")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((host, port))
        
        # 读取SSH banner
        banner = sock.recv(1024).decode('utf-8').strip()
        sock.close()
        
        if banner.startswith('SSH'):
            print(f"✅ SSH服务正常: {banner}")
            return True
        else:
            print(f"⚠️ SSH服务响应异常: {banner}")
            return False
    except socket.timeout:
        print("❌ SSH服务响应超时")
        return False
    except Exception as e:
        print(f"❌ SSH服务测试异常: {str(e)}")
        return False

def test_trace_route(host):
    """测试路由跟踪"""
    print(f"🔍 测试路由跟踪: {host}")
    try:
        if sys.platform.startswith('win'):
            result = subprocess.run(['tracert', '-h', '10', host], 
                                  capture_output=True, text=True, timeout=60)
        else:
            result = subprocess.run(['traceroute', '-m', '10', host], 
                                  capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            print("✅ 路由跟踪完成")
            lines = result.stdout.strip().split('\\n')
            # 显示最后几跳
            print("最后几跳:")
            for line in lines[-3:]:
                if line.strip():
                    print(f"  {line.strip()}")
            return True
        else:
            print("❌ 路由跟踪失败")
            return False
    except Exception as e:
        print(f"❌ 路由跟踪异常: {str(e)}")
        return False

def diagnose_connection_issues(host):
    """诊断连接问题"""
    print("🔍 分析可能的问题原因:")
    
    issues = []
    solutions = []
    
    # 测试基本连通性
    if not test_ping(host):
        issues.append("网络不通")
        solutions.append("检查网络连接和DNS设置")
    
    # 测试SSH端口
    if not test_port(host, 22):
        issues.append("SSH端口(22)无法访问")
        solutions.append("检查ECS安全组是否开放22端口")
        solutions.append("检查ECS实例状态是否为'运行中'")
        solutions.append("检查SSH服务是否启动")
    
    # 测试SSH服务
    if not test_ssh_banner(host):
        issues.append("SSH服务响应异常")
        solutions.append("检查SSH服务配置")
        solutions.append("重启SSH服务")
    
    return issues, solutions

def provide_solutions():
    """提供解决方案"""
    print("\\n" + "="*60)
    print("           🛠️ 解决方案建议")
    print("="*60)
    
    print("\\n📋 阿里云ECS检查清单:")
    print("1. 登录阿里云控制台")
    print("2. 进入ECS管理控制台")
    print("3. 检查实例状态是否为'运行中'")
    print("4. 检查安全组规则:")
    print("   - 入方向规则是否包含SSH(22/22)")
    print("   - 授权对象是否为0.0.0.0/0")
    print("   - 协议类型是否为TCP")
    
    print("\\n🔧 常见解决方法:")
    print("1. 重启ECS实例:")
    print("   - 在ECS控制台选择实例")
    print("   - 点击'重启'按钮")
    print("   - 等待实例重新启动")
    
    print("\\n2. 检查安全组配置:")
    print("   - 进入'网络与安全' -> '安全组'")
    print("   - 找到对应的安全组")
    print("   - 检查入方向规则是否包含:")
    print("     端口范围: 22/22")
    print("     授权对象: 0.0.0.0/0")
    print("     协议类型: TCP")
    
    print("\\n3. 网络排查:")
    print("   - 检查本地网络是否正常")
    print("   - 尝试使用手机热点连接")
    print("   - 检查公司防火墙是否阻止SSH连接")
    
    print("\\n4. SSH客户端替代方案:")
    print("   - 使用阿里云控制台的'远程连接'功能")
    print("   - 使用PuTTY等SSH客户端")
    print("   - 使用VSCode的Remote SSH插件")
    
    print("\\n📞 紧急联系方式:")
    print("   - 阿里云工单系统")
    print("   - 阿里云客服热线: 95187")

def main():
    host = "8.140.59.178"
    
    print("="*60)
    print(f"  阿里云ECS连接诊断工具 - {host}")
    print("="*60)
    print(f"诊断时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*60)
    
    # 执行诊断
    issues, solutions = diagnose_connection_issues(host)
    
    # 输出诊断结果
    print("\\n" + "="*60)
    print("           📊 诊断结果")
    print("="*60)
    
    if issues:
        print("\\n❌ 发现的问题:")
        for i, issue in enumerate(issues, 1):
            print(f"  {i}. {issue}")
    else:
        print("\\n✅ 网络连接正常")
    
    if solutions:
        print("\\n🔧 建议的解决方案:")
        for i, solution in enumerate(solutions, 1):
            print(f"  {i}. {solution}")
    
    # 提供详细解决方案
    provide_solutions()
    
    print("\\n" + "="*60)
    print("诊断完成 - 请根据上述建议进行排查")
    print("="*60)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\\n用户中断诊断")
    except Exception as e:
        print(f"\\n诊断过程发生异常: {str(e)}")